#include "KCPServerContainer.h"
#include "Transmission/KCP/KCPServer.h"
#include <QDebug>
#include <WinSock2.h>
#include <QDateTime>
KCPServer *server;
int64_t lastts = 0;
int fps = 0;
KCPServerContainer::KCPServerContainer(QWidget *parent)
	: QWidget(parent)
	, ui(new Ui::KCPServerContainerClass())
{
	ui->setupUi(this);
	timer = new QTimer(this);
	connect(timer, &QTimer::timeout, this, &KCPServerContainer::Tick);
	timer->start(3);
	server = new KCPServer();
	server->RegisterClientConnectedCallback(&KCPServerContainer::OnServerClientConnected, this);
	server->RegisterClientDisconnectedCallback(&KCPServerContainer::OnServerClientDisconnected, this);
	server->RegisterClientReceivedCallback(&KCPServerContainer::OnServerClientReceived, this);
	server->Initialize(5555);
}

KCPServerContainer::~KCPServerContainer()
{
	delete server;
	delete ui;
}

void KCPServerContainer::Tick()
{
	server->Update();
	if (QDateTime::currentMSecsSinceEpoch() - lastts > 1000)
	{
		lastts = QDateTime::currentMSecsSinceEpoch();
		qDebug() << fps;
		fps = 0;
	}
	fps++;
}

void KCPServerContainer::OnServerClientConnected(KCPClient* client)
{
	//const char* msg = "hello";
	//client->Send((char*)msg, strlen(msg));
	sockaddr_in saddr, caddr;
	client->GetRemoteAddr(&caddr);
	client->GetLocalAddr(&saddr);
	qDebug() << "connect" << ntohs(saddr.sin_port) << "\t" << ntohs(caddr.sin_port);
}

void KCPServerContainer::OnServerClientDisconnected(KCPClient* client)
{
	qDebug() << "disconnect";
}

void KCPServerContainer::OnServerClientReceived(KCPClient* client, char* data, int len)
{
	QByteArray ba(data, len);
	qDebug() << ba;
	client->Send(data, len);
}